package com.jintoufs.web.action.common;

import com.jintoufs.util.JxlsUtils;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public abstract class JxlsHandler {
	private static Logger logger = LoggerFactory.getLogger(JxlsHandler.class);

	/**
	 * @description 根据EXCEL模板,获取文件流
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @param templateName
	 *            excel模板
	 * @param results
	 *            数据结果集
	 * @param downName
	 *            下载文件名
	 * @return InputStream
	 * @throws FileNotFoundException
	 */

	public static void report(HttpServletRequest request,
			HttpServletResponse response, String templateName, Object results, String downName)
			throws IOException {
		XlsCommentAreaBuilder.addCommandMapping("each", EachCommand.class);
		/**
		 * 禁止数据缓存
		 */
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
//		ServletUtils.setDisableCacheHeader(response);
		/**
		 * 设置响应格式
		 */
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-disposition", "attachment;filename=" + new String(downName.getBytes("GBK"), "ISO8859-1"));

		/**
		 * 获取web容器上下文中EXCEL模板文件路径
		 */
		// StringBuilder filePath = new StringBuilder();

		String realPath = request.getServletContext().getRealPath("/report");
		// filePath.append(realPath);
		// filePath.append(File.separator);
		// filePath.append(templateName);
		//
		// logger.debug("The excel template path is :{}", realPath);

		File file = new File(realPath, templateName);
		InputStream is = new FileInputStream(file);
		/**
		 * 流操作
		 */
//		OutputStream os = new FileOutputStream(realPath+"/test.xls");
		OutputStream os=response.getOutputStream();
		try {
			Context context = new Context();
			context.putVar("rs", results);
			JxlsHelper jxlsHelper = JxlsHelper.getInstance();
			Transformer transformer  = jxlsHelper.createTransformer(is, os);
			JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator)transformer.getTransformationConfig().getExpressionEvaluator();
			Map<String, Object> funcs = new HashMap<>();
			funcs.put("utils", new JxlsUtils());    //添加自定义功能
			evaluator.getJexlEngine().setFunctions(funcs);

			JxlsHelper.getInstance().processTemplate(context,transformer);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(
					"Write data into HSSFWorkbook occur exception,caused by:{}",
					e);
		} finally {
			if (is != null) {
				try {
					is.close();
//					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
